<template>
	<view>
		<view class="cascade-select">
			<u-popup v-model="visible" mode="bottom" height="80%" border-radius="14">
				<scroll-view scroll-y="true" style="height: 80%">
					<ly-tree
						v-if="isReady"
						:props="props"
						show-checkbox
						node-key="id"
						:load="loadNode"
						lazy
						accordion
						:expand-on-check-node="expandOnCheckNode"
						@check="handleCheck"
						@check-change="handleCheckChange"
					/>
				</scroll-view>
				<view class="popup-footer ">
					<view class="d-flex ">
						<u-button @click="confirmSelection" type="primary">确定</u-button>
						<u-button @click="hidePopup" type="default">取消</u-button>
					</view>
				</view>
			</u-popup>
		</view>
	</view>
</template>

<script>
import LyTree from '@/components/ly-tree/ly-tree.vue';
import { getNationAreaByParentId } from '@/api/apis.js';
export default {
	name: 'CascadeSelect',
	components: {
		LyTree
	},

	data() {
		return {
			visible: false,
			expandOnCheckNode: false, // 是否展开选中的节点
			isReady: false,
			props: {
				label: 'name',
				children: 'zones',
				isLeaf: 'leaf'
			},
			selectedData: {}
		};
	},
	created() {
		this.isReady = true;
	},
	methods: {
		showPopup() {
			this.visible = true;
		},
		hidePopup() {
			this.visible = false;
		},
		loadNode(node, resolve) {
			if (node.level === 0) {
				getNationAreaByParentId({}).then(res => {
					if (res.code == 10000) {
						setTimeout(() => {
							resolve(res.data);
						}, 1000);
					}
				});
			} else {
				if (node.level > 1) return resolve([]);
				getNationAreaByParentId({
					parentId: node.data.id
				}).then(res => {
					if (res.code == 10000) {
						setTimeout(() => {
							resolve(res.data);
						}, 1000);
					}
				});
			}
		},
		handleCheck(obj) {
			if (obj.node.checked) {
				this.selectedData = obj.data;
			} else {
				this.selectedData = void 0;
			}
		},

		handleClose() {
			this.$emit('close');
		},
		// 只有在"点击"修改的指定节点会触发(也就是说这个方法只会触发一次)，obj中包含当前选中
		handleCheck(obj) {
			// obj: {
			// 	checkedKeys: [9, 5], // 当前选中节点的id数组
			// 	checkedNodes: [{...}, {...}], // 当前选中节点数组
			// 	data: {...}, // 当前节点的数据
			// 	halfCheckedKeys: [1, 4, 2], // 半选中节点的id数组
			// 	halfCheckedNodes: [{...}, {...}, {...}], // 半选中节点的数组
			// 	node: Node {...} // 当前节点实例
			// }

			console.log('handleCheck', obj);
		},

		// 只要节点的选中或半选中状态改变就触发（包括设置默认选中，点击选中/取消选中），其相关的所有父子节点都会触发（也就是说选中一个节点时，触发多次，父子节点的选中状态只要被修改就会触发）
		handleCheckChange(obj) {
			// obj: {
			// 	checked: true, // 节点是否选中
			// 	checkedall: false, // 当前树的所有节点是否全选中
			// 	data: {...}, // 节点数据
			// 	indeterminate: false, // 是否半选中
			// 	node: Node {...} // 节点实例
			// }

			console.log('handleCheckChange', obj);
		}
	}
};
</script>

<style lang="scss" scoped>
::v-deep .ly-tree-node__children {
	position: absolute !important;
	left: 160px !important;
}
::v-deep .ly-tree-node__children {
	top: 16rpx !important;
}
</style>
